import { Space, Tree, Tooltip, Spin, Popconfirm } from 'antd';
import PropTypes from 'prop-types';
import styles from './index.less';
import { useState, useEffect, useImperativeHandle } from 'react';
import { useDispatch } from 'umi';
import { cloneDeep } from 'lodash';
import { namespace, operateTypeObj } from '@/src/newModels/pressureReport/SceneTemplateSettingsM';
import { IconC } from '@/src/components';
import { QuestionCircleOutlined } from '@ant-design/icons';

const LeftContent = (props) => {
  const { onHandlePage, onRef } = props;
  const dispatch = useDispatch();
  const [modelListLoading, setModeListLoading] = useState(false);
  const [isFloatLeft, setIsFloatLeft] = useState(false);
  const [fresh, setFresh] = useState(false); // 是否刷新情景列表
  const [sceneList, setSceneList] = useState([]); // 情景模板列表
  const [currentExpandedKeys, setCurrentExpandedKeys] = useState([]); // 展开的节点
  const [currentSelectedKeys, setCurrentSelectedKeys] = useState([]); // 选中的节点
  const [currentOperateTypes, setCurrentOperateTypes] = useState([]); // 操作权限
  const [leftWidth, setLeftWidth] = useState(264);
  useImperativeHandle(onRef, () => ({
    updateList: () => setFresh(!fresh),
    leftWidth,
  }));
  // 获取右侧详情
  const getSceneTemplateInfo = (sceneId) => {
    dispatch({
      type: `${namespace}/getSceneTemplateDetail`,
      payload: { sceneId },
    });
  };
  // 获取情景模板列表
  const getSceneList = () => {
    setModeListLoading(true);
    // 构建树形数据
    function addKeyToTree(treeData) {
      function traverseTree(data) {
        // 在每个项中添加 key 字段
        data.forEach((item) => {
          item.key = item.sceneId;
          item.title = <Tooltip title={item.des}>{item.sceneName}</Tooltip>;
          if (item.iconType)
            item.icon =
              item.iconType === '1' ? (
                <IconC type='medal' style={{ marginTop: -4, marginLeft: -8 }} />
              ) : item.iconType === '2' ? (
                <IconC type='person' style={{ marginTop: -4, marginLeft: -8 }} />
              ) : null;
          if (item.children && item.children.length > 0) {
            traverseTree(item.children); // 递归遍历子项
          }
        });
      }
      const newTreeData = cloneDeep(treeData);
      traverseTree(newTreeData);
      return newTreeData;
    }
    dispatch({
      type: `${namespace}/getSceneTemplate`,
      payload: {},
      callback: (data) => {
        const resData = addKeyToTree(data);
        setSceneList(resData);
        setCurrentExpandedKeys(resData.map((v) => v.key));
        setCurrentSelectedKeys([resData[0]?.children[0]?.key]);
        getSceneTemplateInfo(resData[0]?.children[0]?.key); // 获取详情
        setCurrentOperateTypes(resData[0]?.children[0]?.operateTypes);
        setModeListLoading(false);
      },
    });
  };
  const handleOnExpand = (expandedKeys, { expanded: bool, node }) => {
    setCurrentExpandedKeys(expandedKeys);
  };
  const handleOnSelect = (selectedKeys, e) => {
    setCurrentSelectedKeys(selectedKeys);
    if (selectedKeys.length !== 0) getSceneTemplateInfo(selectedKeys[0]);
    setCurrentOperateTypes(e.node.operateTypes);
  };
  useEffect(() => {
    getSceneList();
  }, [fresh]);
  const handleOperate = (type) => {
    if (type === 'add') {
      dispatch({
        type: `${namespace}/save`,
        payload: {
          operateType: operateTypeObj.add,
        },
      });
      onHandlePage(2);
    }
    if (type === 'edit') {
      dispatch({
        type: `${namespace}/save`,
        payload: {
          operateType: operateTypeObj.edit,
        },
      });
      onHandlePage(2);
    }
    if (type === 'del') {
      dispatch({
        type: `${namespace}/delSceneTemplateList`,
        payload: {},
        callback: (bool) => {
          if (bool) {
            setFresh(!fresh);
          }
        },
      });
    }
  };

  return (
    <>
      {isFloatLeft ? (
        <div style={{ width: leftWidth }} className={styles.LeftContentCard}>
          <div>情景模板管理</div>
          <IconC
            type={'packUp'}
            title={'展开'}
            isHover={false}
            onClick={() => {
              setIsFloatLeft(false);
              setLeftWidth(264);
            }}
          />
        </div>
      ) : (
        <div className={styles.LeftContent} style={{ width: leftWidth }}>
          <div className={styles.CardContent}>
            <div className={styles.CardHeader}>
              <div>模板管理</div>
              <div>
                <Space>
                  <IconC isDisabled={!currentOperateTypes.includes('add')} type='editNew' title={'新增'} isHover={false} onClick={() => handleOperate('add')} />
                  <IconC onClick={() => handleOperate('edit')} isDisabled={!currentOperateTypes.includes('edit')} type='editNewIcon' title={'编辑'} />
                  <Popconfirm title={'确定删除？'} icon={<QuestionCircleOutlined />} onConfirm={() => handleOperate('del')}>
                    <IconC isDisabled={!currentOperateTypes.includes('del')} title={'删除'} type='deleteNew' />
                  </Popconfirm>
                  <IconC
                    type={'packUp'}
                    title={'收起'}
                    onClick={() => {
                      setIsFloatLeft(true);
                      setLeftWidth(46);
                    }}
                  />
                </Space>
              </div>
            </div>
            <div className={styles.CardTree}>
              <Spin spinning={modelListLoading}>
                <Tree
                  blockNode={true}
                  onSelect={handleOnSelect}
                  onExpand={handleOnExpand}
                  showIcon={true}
                  expandedKeys={currentExpandedKeys}
                  selectedKeys={currentSelectedKeys}
                  switcherIcon={<></>}
                  treeData={sceneList}
                />
              </Spin>
            </div>
          </div>
        </div>
      )}
    </>
  );
};
LeftContent.propTypes = {
  onHandlePage: PropTypes.func, // 切换页面
  onRef: PropTypes.object, // 暴露实例
};
export default LeftContent;
